<?php
/**
 * Created by PhpStorm.
 * User: zhangwei
 * Date: 2017/7/5
 * Time: 22:43
 */

namespace System\Controller;

use think\Controller;

//TODO 继承基类控制器

class RegionController  extends Controller {
	
	//根据条件获取区域级别(后端页面选择区域特效用）
	public function getRegion($level=1,$parent_id = 0){
		$where = array(
			'level'		=> $level,
			'parent_id'	=> $parent_id,
		);
		
		$region_list = M('Region')->where($where)->select();
		
		$html = '';
		if($region_list){
			exit(json_encode($region_list,JSON_UNESCAPED_UNICODE));
		}else{
			exit(false);
		}
	}
	
	
	//区域列表包括省市县
	public function region_List() {
		
		$model = M('Region');
		$where['level'] = 1;
		$where['id']	= array('in', array('1', '3102', '338')); //限制 只显示 1 2102 228 省 市 县 的数据，全显示可关闭此项
		
		$result1 = $model->where($where)->select();
		
		foreach ($result1 as $key => $value) {
			$arr[$key]['name']		  = $value['name'];
			$arr[$key]['province_id'] = $value['id'];
			$result2 = $model -> where("parent_id={$value['id']}") -> select();
			foreach ($result2 as $key2 => $value2) {
				$arr[$key]['sub'][$key2]['name']	= $value2['name'];
				$arr[$key]['sub'][$key2]['city_id'] = $value2['id'];
				$result3 = $model->where("parent_id={$value2['id']}")->select();
				foreach ($result3 as $key3 => $value3) {
					$arr[$key]['sub'][$key2]['sub'][$key3]['name']		  = $value3['name'];
					$arr[$key]['sub'][$key2]['sub'][$key3]['district_id'] = $value3['id'];
				}
			}
		}
		
		// dump($arr);
		exit(json_encode($arr,true));
	}

// 城市信息转josn 只要市的信息
	function get_city_list() {
		
		$model = M('Region');
		
		$where['level'] = 2; // 查询市
		$where['id']	= array('not in', array('2', '300', '339', '569', '10544', '10779','31930','32380')); // 去除北京、天津、上海,重庆的市辖区和县
		$where2['id']	= array('in', array('1', '338', '10543','31929'));  // 查询北京 天津 上海,重庆四个城市，因为和上边的语句冲突，所以分开查询
		
		$result1 = $model -> where($where)  -> select();
		$result2 = $model -> where($where2) -> select();
		
		$result	 = array_merge($result1, $result2);
		
		$obj	 = new \Org\Util\Pinyin();
		$sort	 = array();
		$topCity = array('1', '338', '10543');  //设置热门城市,可以设置多个
		
		foreach ($result as $key => $value) {
			// 去掉城市的市
			if (preg_match('/市/', $value['name'])) {
				$arr[$key]['city'] = preg_replace('/市/', '', $value['name']);
			} else {
				$arr[$key]['city'] = $value['name'];
			}
			$arr[$key]['pinyin'] = $obj->getAllPY($arr[$key]['city']);
			$arr[$key]['id']	 = $value['id'];
			foreach ($topCity as $key2 => $value2) {
				if ($arr[$key]['id'] === $value2) {
					$arr2[$key2]['pinyin']	= $arr[$key]['pinyin'];
					$arr2[$key2]['id']		= $arr[$key]['id'];
					$arr2[$key2]['city']	= $arr[$key]['city'];
				}
			}
			
			$sort[] = $arr[$key]['pinyin'];
			
		}
		
		array_multisort($sort, SORT_ASC, SORT_STRING, $arr); //按照拼音进行排序
		sort($arr2);  //重排数组，下标重新生成,方便转换的json没有下标显示
		
		$res['topCitys'] = $arr2;
		$res['citys'] = $arr;
		
		exit(json_encode($res,true));
		
	}
	
	
}